import React, { useState } from 'react';
import { Card, Button, Form, Input, message, Space, Divider } from '@/utils/antd-imports';
import { userApi } from '@/api/userApi';
import captchaApi from '@/api/captchaApi';

const LoginTest = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [captchaLoading, setCaptchaLoading] = useState(false);
  const [captchaData, setCaptchaData] = useState(null);
  const [loginResult, setLoginResult] = useState(null);

  // 生成验证码
  const generateCaptcha = async () => {
    setCaptchaLoading(true);
    try {
      const response = await captchaApi.generateCaptcha();
      if (response.code === 200) {
        setCaptchaData(response.data);
        message.success('验证码生成成功');
        console.log('验证码数据:', response.data);
      } else {
        message.error(response.message || '验证码生成失败');
      }
    } catch (error) {
      message.error('验证码生成失败');
      console.error('验证码生成错误:', error);
    } finally {
      setCaptchaLoading(false);
    }
  };

  // 测试登录
  const testLogin = async (values) => {
    setLoading(true);
    setLoginResult(null);
    
    try {
      console.log('登录请求数据:', values);
      
      const loginData = {
        username: values.username,
        password: values.password,
        captchaId: captchaData?.captchaId,
        captchaCode: values.captchaCode
      };
      
      console.log('发送登录请求:', loginData);
      
      const response = await userApi.login(loginData);
      
      console.log('登录响应:', response);
      
      setLoginResult({
        success: true,
        data: response
      });
      
      if (response.code === 200) {
        message.success('登录成功');
      } else {
        message.error(response.message || '登录失败');
      }
    } catch (error) {
      console.error('登录错误:', error);
      setLoginResult({
        success: false,
        error: error.message || '登录失败'
      });
      message.error(error.message || '登录失败');
    } finally {
      setLoading(false);
    }
  };

  // 测试Token验证
  const testTokenValidation = async () => {
    try {
      const response = await userApi.validateToken();
      console.log('Token验证响应:', response);
      message.success('Token验证成功');
    } catch (error) {
      console.error('Token验证错误:', error);
      message.error('Token验证失败');
    }
  };

  return (
    <div style={{ padding: '24px', maxWidth: '800px', margin: '0 auto' }}>
      <h1>登录功能测试页面</h1>
      
      <Card title="验证码测试" style={{ marginBottom: 16 }}>
        <Space direction="vertical" style={{ width: '100%' }}>
          <Button 
            type="primary" 
            onClick={generateCaptcha}
            loading={captchaLoading}
          >
            生成验证码
          </Button>
          
          {captchaData && (
            <div>
              <p><strong>验证码ID:</strong> {captchaData.captchaId}</p>
              <div 
                style={{ 
                  width: '120px', 
                  height: '40px', 
                  border: '1px solid #d9d9d9', 
                  borderRadius: '6px',
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center',
                  cursor: 'pointer',
                  backgroundColor: '#fafafa',
                  overflow: 'hidden'
                }}
                onClick={generateCaptcha}
                title="点击刷新验证码"
              >
                <img
                  src={captchaData.captchaImage}
                  alt="验证码"
                  style={{ 
                    width: '100%', 
                    height: '100%', 
                    objectFit: 'cover',
                    cursor: 'pointer'
                  }}
                />
              </div>
            </div>
          )}
        </Space>
      </Card>

      <Card title="登录测试" style={{ marginBottom: 16 }}>
        <Form
          form={form}
          layout="vertical"
          onFinish={testLogin}
          disabled={!captchaData}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          
          <Form.Item
            label="验证码"
            name="captchaCode"
            rules={[{ required: true, message: '请输入验证码' }]}
          >
            <Input placeholder="请输入验证码" maxLength={4} />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={loading}
                disabled={!captchaData}
              >
                测试登录
              </Button>
              <Button onClick={generateCaptcha}>
                刷新验证码
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card title="Token验证测试" style={{ marginBottom: 16 }}>
        <Button onClick={testTokenValidation}>
          测试Token验证
        </Button>
      </Card>

      {loginResult && (
        <Card title="登录结果">
          <div style={{ backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '4px' }}>
            <h4>响应数据:</h4>
            <pre style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
              {JSON.stringify(loginResult, null, 2)}
            </pre>
          </div>
        </Card>
      )}

      <Divider />
      
      <Card title="调试信息">
        <div style={{ fontSize: '12px', color: '#666' }}>
          <p><strong>API基础URL:</strong> {import.meta.env.VITE_API_BASE_URL || 'http://localhost:8087'}</p>
          <p><strong>当前Token:</strong> {localStorage.getItem('token') || '无'}</p>
          <p><strong>当前用户:</strong> {localStorage.getItem('username') || '无'}</p>
          <p><strong>用户类型:</strong> {localStorage.getItem('userType') || '无'}</p>
        </div>
      </Card>
    </div>
  );
};

export default LoginTest;
